package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class MiniReqProcessor extends Thread {
    // 这两个值都通过外部传值进来
    private Socket socket;//每个请求对应一个socket
    private Mapper mapper;

    public MiniReqProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            Servlet servlet = matcherServlet(request.getUrl());
            // 静态资源处理
            if(servlet == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                servlet.service(request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 拿mapper中的servlet
     */
    private Servlet matcherServlet(String url) {

        Host[] hosts=mapper.getHosts();
        for(Host host:hosts){

            Context[] contexts=host.getContexts();

            for(Context context:contexts){

                String path="/"+context.getPath();
                if(url.startsWith(path)) {
                    String servletPath=url.replace(path, "");
                    Map<String, HttpServlet> wrappers = context.getWrappers();
                    if (null != wrappers.get(servletPath))
                        return wrappers.get(servletPath);
                }
            }
        }
        return null;
    }
}
